#include <func.h>
#include "head.h"
//服务端接收客户端发来的文件
//结构体之后放到头文件里去

// int upload(MYSQL *db, char* argv, char* pwd, int netFd){
//     //puts file
//     //pwd /usr1
//     char arr[100] = "";
//     strcpy(arr, argv);
//     char* command = strtok(arr, " ");
//     char* fileName = strtok(NULL, " ");
//     char filePath[100] = {0};
//     sprintf(filePath, ".%s%s%s", pwd, "/", fileName);
//     //得到文件大小
//     int dataLength;
//     long fileSize;
//     recvn(netFd, &dataLength, sizeof(int));
//     recvn(netFd, &fileSize, dataLength);
//     printf("filesize = %lu\n", fileSize);
//     int fd = open(filePath, O_RDWR|O_CREAT, 0666);
//     ERROR_CHECK(fd, -1, "open");
//     ftruncate(fd, fileSize);
//     char *p = (char *)mmap(NULL, fileSize, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
//     recvn(netFd, p, fileSize);
//     munmap(p, fileSize);
//     close(fd);
// }

int upload(MYSQL *db, char *argv, char *pwd, char *usr_name, int netFd){
    //puts file1
    //./Catalog/md5
    //pwd /usr1/dir1
    int md5Length;
    char md5[50] = {0};
    recvn(netFd, &md5Length, sizeof(int));
    recvn(netFd, md5, md5Length); 
    char filePath[100] = {0};
    sprintf(filePath, "./Catalog/%s", md5);
    int fd = open(filePath, O_RDWR|O_CREAT|O_EXCL, 0666);  

    //不管是否存在都需将其插入数据库
    char arr[100] = "";//从puts file1中得到file1
    strcpy(arr, argv);
    char* command = strtok(arr, " ");
    char* fileName = strtok(NULL, " ");
    char file_name[50] = {0};
    // file_name = '/usr1/dir1/file1'
    sprintf(file_name, "%s/%s", pwd, fileName);
    //得到pre_id
    int pre_id = getIdFromFileName(db, pwd);
    insertCatalog(db, file_name, usr_name, pre_id, md5);

    if(fd == -1){//文件存在，直接插入数据库
        send(netFd, "0", 1, MSG_NOSIGNAL);
    }
    else{//文件不存在，准备接收
        send(netFd, "1", 1, MSG_NOSIGNAL);
        int dataLength;
        long fileSize;
        recvn(netFd, &dataLength, sizeof(int));
        recvn(netFd, &fileSize, dataLength);
        printf("filesize = %lu\n", fileSize);
        ftruncate(fd, fileSize);
        char *p = (char *)mmap(NULL, fileSize, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
        recvn(netFd, p, fileSize);
        munmap(p, fileSize);
        close(fd);
        send(netFd, "1", 1, MSG_NOSIGNAL);
    }
    return 0;
}

